package cn.kgc.factory;

import cn.kgc.service.AccountService;
import cn.kgc.utils.TransactionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author Rock
 * @create 2020-08-25 11:49
 */
@Component("beanFactory")
public class BeanFactory {
    @Autowired
    private AccountService accountService;
    @Autowired
    private TransactionUtil transactionUtil;
    /**
     * 动态生成AccountService对象
     * @return
     */
    public AccountService getAccountService(){
        return (AccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader()
                , accountService.getClass().getInterfaces(), new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object returnValue=null;
                        try{
                            transactionUtil.beginTransaction();
                            //执行业务操作
                            returnValue=method.invoke(accountService,args);
                            transactionUtil.commitTransaction();
                            System.out.println("执行业务");
                        }catch (Exception e){
                            e.printStackTrace();
                            transactionUtil.rollbackTransaction();
                            System.out.println("回滚了");
                        }finally{
                            transactionUtil.closeTransaction();
                            System.out.println("资源释放");
                        }
                        return  returnValue;
                    }

                });
    }

}
